<template>
  <div class="page white-stage">
    <div class="container my-card-main">
      <div class="group upload-main">
        <div class="upload-body" >
          <div class="cell upload-qrcode" id="pickfiles">
            <div>
              <div class="upload-qrcode-body"  v-if="!card.card_qrcode">
                <div class="upload-qrcode-tip">
                  <i class="upload-ico">+</i>
                  <span class="upload-qrcode-txt">上传微信二维码</span>
                </div>
              </div>

              <div class="upload-qrcode-body"  v-if="card.card_qrcode">
                <img :src="card.card_qrcode"/>
              </div>
            </div>
          </div>

          <div class="cell my-name border-bottom txt-center">
            <input type="text" v-model="card.name" placeholder="姓名"/>
          </div>

          <div class="cell my-phone border-bottom">
            <input type="text" v-model="card.card_mobile" placeholder="手机"/>
          </div>

          <div class="cell my-desc border-radius mgt transparent">
            <textarea placeholder="个人介绍" v-model="card.card_user_desc"></textarea>
          </div>
        </div>
      </div>

      <div class="group">
        <div class="cell mgt">
          <span class="save-btn scrm-default-btn" @click="saveCard">保存</span>
        </div>
      </div>
    </div>

    <x-dialog v-model="this.$store.state.app.dialogShow">
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
  </div>
</template>

<script>
import store from '../store'
import envFuncs from '@/config/base'
let env = envFuncs.getParams()
import XDialog from 'vux/src/components/x-dialog'
import {showDialog, hideDialog} from '../lib/dialog'
import { isPhone } from '../lib/validate-rules'
import axios from 'axios'
import { mapState, mapActions } from 'vuex'

export default{

  data () {
   return {
     card: {},
     my: {
       name: ''
     },
     errors: {
     },
     finish: true,
     countDown: 60,
     verifyCode: null,
     isQiniuInstalled: false
   }
  },

  methods: {
    loadScript(url, callback) {
      var script = document.createElement('script')
      script.type = 'text/javascript'
      if (typeof(callback) !== 'undefined') {
        if (script.readyState) {
            script.onreadystatechange = function () {
              if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null
                callback()
              }
            }
        } else {
          script.onload = function () {
            callback()
          }
        }
      }
      script.src = url
      document.body.appendChild(script)
    },
    hideDialog: hideDialog,
    saveCard () {
      let that = this
      if (isPhone(this.card.card_mobile) === false) {
        return showDialog('您填写的手机号码无效！')
      }
      //
      // this.verifySmscode({ mobile_num: this.card.card_mobile, verifycode: this.verifyCode })
      //   .then((data) => {
      //     if (data.errcode === 0) {
      store.dispatch('saveCard', that.card).then((response) => {
        if (response.data.errcode === 0) {
          let loginUser = this.$store.state.app.user
          loginUser.name = this.card.name
          store.commit('UPDATE_USER', loginUser)
          showDialog('保存成功!')
        } else {
          console.log('系统出错请联系管理员:', JSON.stringify(response.data))
        }
        showDialog(response.data.errmsg)
      }).catch((error) => {
        showDialog(data.errmsg)
        console.log(error)
      })
        //   } else {
        //     showDialog(data.errmsg)
        //   }
        // }).catch(() => {
        //   showDialog('系统错误！请联系管理员!')
        // })
    },
    send () {
      this.sendSmsCode({ mobile_num: this.card.card_mobile, verifycode: this.verifyCode })
      this.finish = false
      this.cid = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown --
          if (this.countDown < 10) {
            this.countDown = '0' + this.countDown
          }
        } else {
          clearInterval(this.cid)
          this.finish = true
          this.countDown = 60
        }
      }, 1000)
    },
    getCard () {
      let that = this
      store.dispatch('getCard').then(function (response) {
        that.card = response.data.results
        that.card.name = that.card.name || that.loginUser.name
      })
    },
    uploadQrcode () {
      if (this.isQiniuInstalled === true) {
        let uptoken_url = env.CRM_API_HOST + '/users/' + this.token + '/upload_token'
        let that = this
        try {
          axios.get(uptoken_url).then((response) => {
            if (response.data.errcode === 0) {
              let uptoken = response.data.results.token
              let domain = response.data.results.domain
              let uploader = Qiniu.uploader({
                 runtimes: 'html5,flash,html4',
                 browse_button: 'pickfiles',
                //  container: 'container',
                 drop_element: 'container',
                 max_file_size: '1000mb',
                 flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
                 dragdrop: true,
                 chunk_size: '1000mb',
                 multi_selection: false,
                //  uptoken_url: $('#uptoken_url').val(),
                 uptoken:uptoken,
                 domain: domain,
                 get_new_uptoken: false,
                 // downtoken_url: '/downtoken',
                 // unique_names: true,
                 // save_key: true,
                 // x_vars: {
                 //   'id': '1234',
                 //   'time': function(up, file) {
                 //     var time = (new Date()).getTime();
                 //     // do something with 'time'
                 //     return time;
                 //   },
                 // },
                 auto_start: true,
                 log_level: 5,
                 init: {
                   'FilesAdded': function(up, files) {
                    //  $('table').show();
                    //  $('#success').hide();
                    //  plupload.each(files, function(file) {
                    //    var progress = new FileProgress(file, 'fsUploadProgress');
                    //    progress.setStatus("ç­‰å¾…...");
                    //    progress.bindUploadCancel(up);
                    //  });
                   },
                   'BeforeUpload': function(up, file) {
                   that.$vux.loading.show({
                     text: 'Loading'
                   })
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                    //  if (up.runtime === 'html5' && chunk_size) {
                    //    progress.setChunkProgess(chunk_size);
                    //  }
                   },
                   'UploadProgress': function(up, file) {
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                    //  progress.setProgress(file.percent + "%", file.speed, chunk_size);
                    console.log(file,1)
                   },
                   'UploadComplete': function(event, files, info) {
                    //  $('#success').show();
                    console.log('success', file, info)
                    let file = files.pop();
                    that.card.card_qrcode = domain+'/'+file.name;
                    that.$vux.loading.hide();
                   },
                   'FileUploaded': function(up, file, info) {
                    //  var progress = new FileProgress(file, 'fsUploadProgress');
                    //  progress.setComplete(up, info);
                   },
                   'Error': function(up, err, errTip) {
                    //  $('table').show();
                    //  var progress = new FileProgress(err.file, 'fsUploadProgress');
                    //  progress.setError();
                    //  progress.setStatus(errTip);
                   }
                     // ,
                     // 'Key': function(up, file) {
                     //   var key = "";
                     //   // do something with key
                     //   return key
                     // }
                 }
               });

               uploader.bind('FileUploaded', function() {
                 console.log('hello man,a file is uploaded');
               });

              // domain为七牛空间对应的域名，选择某个空间后，可通过 空间设置->基本设置->域名设置 查看获取
              // uploader为一个plupload对象，继承了所有plupload的方法
              console.log('============初始化qiniu完毕============')
            } else {
              console.log('初始化qiniu出错!', JSON.stringify(response.data))
            }
          }).catch((errcode)=>{
            console.log(errcode)
          });

        } catch(e) {
          console.log(e)
        }

        // let response = {
        //   "errcode": 0,
        //   "errmsg": "接口调用成功!",
        //   "results": {
        //   "token": "6EZmwsqQYeHvlaA44_LwiBAePez-rjpOv4jwg4t4:cYU1nbpCi9jzuejkwhstLZ9wWeQ=:eyJzY29wZSI6Im1xY3JtIiwiZGVhZGxpbmUiOjE0OTA3MjEwNjEsInVwSG9zdHMiOlsiaHR0cDpcL1wvdXAucWluaXUuY29tIiwiaHR0cDpcL1wvdXBsb2FkLnFpbml1LmNvbSIsIi1IIHVwLnFpbml1LmNvbSBodHRwOlwvXC8xODMuMTM2LjEzOS4xNiJdfQ==",
        //   "domain": "http://ocuvbzm86.bkt.clouddn.com"
        //   }
        // }
        }

    },
    initQiniuApiCallback () {
      console.log('初始化qiniu')
      console.log(window['Qiniu'], this)
      this.isQiniuInstalled = true
      this.uploadQrcode()
    },
    ...mapActions({
      'sendSmsCode': 'sendSmsCode',
      'verifySmscode': 'verifySmscode',
    })
  },
  mounted () {
    let that = this;

    that.loadScript(env.PUPLOAD_CDN, function () {
      that.loadScript(env.QINIU_CDN,function () {
        that.initQiniuApiCallback();
      });
    });

    this.callJsApi('biz.navigation.setTitle',{title:'我的名片'});
    this.getCard();
  },

  components:{
    XDialog
  },
  computed:{
    loginUser () {
      return this.$store.state.app.user;
    },

    token () {
      return this.$store.state.app.token;
    },

    domain () {
      return this.$store.state.app.token;
    }
  }
}
</script>


<style lang="less">
  @import "../less/mixins/placeholder.less";
  @import "../less/index.less";

  .my-card-main {
    width:100%;
    background-color: white;

    .upload-main{
      width:82%;
      margin: 10px auto 0;
      border:1px solid #97D2FF;
      display: block;
      background: url("@{host}/my_card.png") no-repeat 0 0;
      background-size: 100% auto;

      .upload-body{
        width: 70%;
        padding-bottom: 10px;
        margin: 0 auto;
      }
    }



    .upload-qrcode-tip {
      display: inline-block;
      margin: 4rem auto;
      i {
        font-style: normal;
      }
    }

    .upload-qrcode {
      @upload-qrcode-size: 150px;
      width: @upload-qrcode-size;
      height: @upload-qrcode-size;
      background-color: #79B3DC;
      opacity: 0.85;
      margin:20px auto ;
      // display: table;
      // table-layout: fixed;
      overflow: hidden;

      .upload-qrcode-body{

        width: 100%;
        vertical-align: middle;
        height: @upload-qrcode-size;

        &>*{
          display: block;
          font-style: normal;
          text-align: center;
          height: 100%;
          object-fit: cover;
          width: 100%;
          color:white;
        }
      }
    }

    .cell {

      input{
        border:none;
        display: block;
        line-height: 16px;
        width: 100%;
        padding: 5px 0;
        font-size: 14px;
        text-align: center;
        background: none;

        .placeholder({

        })
      }

      textarea{
        text-align: center;
      }

      &.border-bottom{
        border-bottom: 1px solid #97D2FF;
        margin: 10px 0;
      }

      &.border-radius{
        border: 1px solid #97D2FF;
        margin: 10px 0;
        border-radius: 4px;
      }

      &.mgt{
        margin-top: 30px;
      }



      textarea {
        border: 0;
        display: block;
        width: 100%;
        font-size: 14px;
        background-color:rgba(255,255,255,0.1);

        @textarea-size:130px;

        height: @textarea-size;

        .placeholder({
          text-align: center;
          font-size: 14px;
          line-height: @textarea-size;
        })

      }


    }

    .verify-code {
      overflow: hidden;
      padding-bottom: 10px;

      input {
        text-align: right;
        width: 146px;
        float: left;
        height: 23px;
        line-height: 23px;
        outline: none;
      }

      .border-bottom {
        border-bottom: 1px solid #97D2FF;
      }
    }

    .default-btn {
      width: 80px;
      font-size: 12px;
      cursor: pointer;
      display: block;
      // background-color: #39ADFF;
      color: #97D2FF;
      text-align: center;
      margin: 0 auto;
      border-radius: 4px;
      padding: 6px 0;
      font-size: 14px;
      border: 1px solid #97D2FF;
    }

    .save-btn{
      width: 90%;
      display: block;
      color: white;
      text-align: center;
      margin: 0 auto;
      border-radius: 4px;
    }
  }
</style>
